package cn.lingyangwl.agile.msg.push.api.handler;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.lingyangwl.agile.msg.push.api.model.mq.MsgPushMQ;
import cn.lingyangwl.agile.msg.push.api.model.rqrs.MsgPushParam;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Service
@Slf4j
@Component
@ConditionalOnClass(RabbitTemplate.class)
public class MsgPushToMqHandler implements IMsgPushAsyncHandler {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void push(MsgPushParam msgPushParam, LocalDateTime planPushDate) {
        String message = MsgPushMQ.build(msgPushParam).toMessage();
        if (Objects.nonNull(planPushDate) && LocalDateTime.now().isBefore(planPushDate)) {
            log.info("push delayed msg to mq, msg: {}", JSON.toJSONString(msgPushParam));
            long ms = LocalDateTimeUtil.between(LocalDateTime.now(), planPushDate, ChronoUnit.MILLIS);
            if (ms >= Integer.MAX_VALUE) {
                throw new BizException("planPushDate: {} is too long", planPushDate);
            }
            rabbitTemplate.convertAndSend(MsgPushMQ.DELAYED_EXCHANGE, "", message, correlationData -> {
                correlationData.getMessageProperties().setDelay(Integer.valueOf(ms + ""));
                return correlationData;
            });
            return;
        }
        log.info("push msg to mq, msg: {}", JSON.toJSONString(msgPushParam));
        rabbitTemplate.convertAndSend(MsgPushMQ.EXCHANGE, MsgPushMQ.KEY, message);
    }
}
